package com.ins.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ins
 * @version 1.0
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    /**
     * 这里手动注入异步线程池
     */
    @Override
    public Executor getAsyncExecutor() {
        int m = Runtime.getRuntime().availableProcessors() * 5;
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池数量
        executor.setCorePoolSize(m);
        //最大线程数量
        executor.setMaxPoolSize(m);
        //线程池的队列容量
        executor.setQueueCapacity(10000);
        //线程名称的前缀
        executor.setThreadNamePrefix("ms-async-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间(默认值 60),当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        executor.initialize();
        return executor;
    }
}
